package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.GoodsImgDao;
import entity.Goods;
import entity.GoodsClass;
import entity.GoodsLabel;
import entity.UserAddress;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import service.GoodLabelService;
import service.GoodsClassService;
import service.GoodsService;
import service.UserAddressService;
import service.UserService;

/**
 * Servlet implementation class GoodsServlet
 */
@WebServlet("*.goods")
public class GoodsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	GoodsClassService gcService = new GoodsClassService();
	GoodsService goodService = new GoodsService();
	GoodLabelService goodLabelService = new GoodLabelService();
	UserAddressService userAddressService = new UserAddressService();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GoodsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uri = request.getRequestURI();
		int index = uri.lastIndexOf("/");
		String action = uri.substring(index+1);
		switch(action) {
		case "add.goods":
			addGoods(request,response);
			break;
		case "getGoodsNameByTwo.goods":
			getGoodsNameByTwoClass(request,response);
			break;
		case "getGoodsByGoodId.goods":
			getGoodsByGoodId(request,response);
			break;
		case "search.goods":
			getGoodsByLike(request,response);
			break;
		case "page.goods":
			getGoodsByPage(request,response);
			break;
		case "detail.goods":
			getGoodsByGoodsDetail(request, response);
		case "shop.goods":
			shopCenter(request, response);
		default:
			break;
		}
	}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	protected void shopCenter(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int id = 1;
		if((String) request.getSession().getAttribute("loginUserId")!=null) {
			id = Integer.parseInt((String) request.getSession().getAttribute("loginUserId"));
		}
		UserService userService = new UserService();
		String userType = userService.getTypeByUserId(id);
		if(userType.equals("shop")) {
			response.getWriter().write("success");
		} else if(userType.equals("user")){
			response.getWriter().write("error");
		} else {
			response.getWriter().write("warning");
		}
		
	}
	
	//添加一件商品
	protected void addGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String goodName = request.getParameter("goodName");
		String goodLabel = request.getParameter("goodLabel");
		int goodClassId = 2;
		if(request.getParameter("twoClassList") != null && !request.getParameter("twoClassList").equals("")) {
			goodClassId = Integer.parseInt(request.getParameter("twoClassList"));
		}
		double goodPrice = Double.parseDouble(request.getParameter("goodPrice"));
		int goodStock = Integer.parseInt(request.getParameter("goodStock"));
		String goodInfo = request.getParameter("goodInfo");
		String goodDesc = request.getParameter("articleContent");
		
		GoodsClass goodsClass = gcService.getClassById(goodClassId); 
		GoodsLabel label = new GoodsLabel(goodLabel);
		
		List<GoodsLabel> labelList = new ArrayList<>();
		labelList.add(label);
		int id=Integer.parseInt((String) request.getSession().getAttribute("loginUserId"));
		Goods good = new Goods(goodName, goodPrice, goodInfo, id, goodStock, goodsClass, goodDesc, labelList);
		
		goodService.addGoods(good, label);
		
		response.getWriter().write("ok");
	}
	
	//根据二级分类id获取商品
	protected void getGoodsNameByTwoClass(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int twoClassId = Integer.parseInt(request.getParameter("twoClassId"));
		int id=Integer.parseInt((String) request.getSession().getAttribute("loginUserId"));
		List<Goods> goodList = goodService.getGoodByTwoClassId(id, twoClassId);
		
		//将json所需的包放到lib里面,将list转换为json
        JSONArray json=JSONArray.fromObject(goodList);
        //响应前台页面
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json");
        PrintWriter out=response.getWriter();
        out.println(json);//打印json，为了前台页面获取
        out.flush();//刷新流
        out.close();//关闭流
	}
	
	//根据商品id获取商品信息
	protected void getGoodsByGoodId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int goodId = Integer.parseInt(request.getParameter("goodId"));
		Goods goods = goodService.getGoodByGid(goodId);
		
		//将json所需的包放到lib里面,将list转换为json
		//如果只是一个对象用JSONObject，如果是集合用JSONArray
        JSONObject json=JSONObject.fromObject(goods);
        
        //响应前台页面
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json");
        PrintWriter out=response.getWriter();
        out.println(json);//打印json，为了前台页面获取
        out.flush();//刷新流
        out.close();//关闭流
	}
	
	//查找商品根据近似度 
	protected void getGoodsByLike(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String likeword = request.getParameter("likeword");
		request.getSession().setAttribute("likeword", likeword);
		
		int in1 = 1;
		List<Goods> goodsByPage = goodService.getGoodsByPage((in1-1)*12, in1*12+1, likeword);
		
		int goodListSize = goodService.getCountByByLike(likeword)/13+1;
		
		if(goodListSize>0) {
			request.setAttribute("goodsList", goodsByPage);
			request.setAttribute("goodListSize", goodListSize+"");
		}
		request.getRequestDispatcher("produceSearch.jsp").forward(request, response);
	}
	
	//查找通过分页内容进行查找
	protected void getGoodsByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String likeword = (String)request.getSession().getAttribute("likeword");
		int in1 = Integer.parseInt(request.getParameter("pageIndex"));
		List<Goods> goodsByPage = goodService.getGoodsByPage((in1-1)*12, in1*12+1, likeword);
		
		//将json所需的包放到lib里面,将list转换为json
		//如果只是一个对象用JSONObject，如果是集合用JSONArray
		JSONArray json=JSONArray.fromObject(goodsByPage);
        
        //响应前台页面
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/json");
        PrintWriter out=response.getWriter();
        out.println(json);//打印json，为了前台页面获取
        out.flush();//刷新流
        out.close();//关闭流
	}
	
	//根据商品id获取商品详情
	protected void getGoodsByGoodsDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int id=Integer.parseInt( request.getParameter("goodId"));
		Goods goodDetail = goodService.getGoodByGoodDetail(id);
		request.setAttribute("goodDetail", goodDetail);
		request.getRequestDispatcher("goodsDetail.jsp").forward(request, response);
	}
     
}
